package org.jadelyre.jade;

import org.jadelyre.core.NodeAddress;
import org.jadelyre.core.exception.JadeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, JadeServer> {
    private static final Logger logger = LoggerFactory.getLogger(AcceptCompletionHandler.class);
    @Override
    public void completed(AsynchronousSocketChannel asynchronousSocketChannel, JadeServer jadeServer) {

        //可以做一些文章
        try {
            InetSocketAddress inetSocketAddress = (InetSocketAddress) asynchronousSocketChannel.getRemoteAddress();
            NodeAddress nodeAddress = new NodeAddress(inetSocketAddress.getHostString(), inetSocketAddress.getPort());
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 64 * 1024);
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 64 * 1024);
            asynchronousSocketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);

            JadeChannel jadeChannel = new JadeChannel(jadeServer, asynchronousSocketChannel, nodeAddress);
            asynchronousSocketChannel.read(jadeChannel.getReadCompletionHandler().getReadByteBuffer(), jadeChannel,jadeChannel.getReadCompletionHandler());
        } catch (IOException e) {
            if (logger.isErrorEnabled()) {
                logger.error(e.toString());
            }
            throw new JadeException(e);
        } finally {
            if (jadeServer.isStarted()) {
                //当前连接建立成功后，接收下一个请求建立新的连接
                jadeServer.getAsynchronousServerSocketChannel().accept(jadeServer, this);
            }
        }
    }

    @Override
    public void failed(Throwable exc, JadeServer jadeServer) {
//        System.out.println("AcceptCompletionHandler:" + exc.toString());
        if (logger.isDebugEnabled()) {
            logger.debug("接受连接失败，可能当前服务正在关闭:{}", exc.toString());
        }
        if (jadeServer.isStarted()) {
            //当前连接建立成功后，接收下一个请求建立新的连接
            jadeServer.getAsynchronousServerSocketChannel().accept(jadeServer, this);
        }
    }
}
